<template>
  <div class="drawer-content-wrapper">
    <el-form
      ref="formRef"
      :model="customerForm"
      :rules="rules"
      label-width="120px"
      label-position="right"
    >
      <!-- 基本信息 -->
      <div class="form-section">
        <h3 class="form-section-title">基本信息</h3>
        <div class="form-container">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="客户类型" prop="customer_type">
                <el-radio-group v-model="customerForm.customer_type">
                  <el-radio :label="16">企业客户</el-radio>
                  <el-radio :label="15">个人客户</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="录入人" prop="creator_id">
                <el-input v-model="customerForm.creator_name" readonly placeholder="请选择录入人">
                  <template #append>
                    <el-button @click="selectCreator">选择</el-button>
                  </template>
                </el-input>
                <input type="hidden" v-model="customerForm.creator_id" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="客户名称" prop="name">
                <el-input v-model="customerForm.name" placeholder="请输入客户名称"></el-input>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="客户来源" prop="source_id">
                <CustomerSourceSelect v-model="customerForm.source_id" :options="sourceOptions" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="证件号码" prop="tax_num">
                <el-input
                  v-model="customerForm.tax_num"
                  :placeholder="
                    customerForm.customer_type === 16 ? '请输入统一信用代码' : '请输入身份证号码'
                  "
                ></el-input>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="客户等级" prop="grade_id">
                <CustomerGradeSelect v-model="customerForm.grade_id" :options="gradeOptions" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="是否主客户" prop="is_primary">
                <el-radio-group v-model="customerForm.is_primary" @change="handlePrimaryChange">
                  <el-radio :label="0">否</el-radio>
                  <el-radio :label="1">是</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>

            <el-col :span="12" v-if="customerForm.is_primary === 0">
              <el-form-item label="选择主客户">
                <el-input v-model="primaryCustomerName" readonly placeholder="请选择主客户">
                  <template #append>
                    <el-button @click="openPrimaryCustomerSelector">选择</el-button>
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 隐藏客户分组代码字段 -->
          <input type="hidden" v-model="customerForm.group_code" />

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="负责人姓名" prop="controller_name">
                <el-input
                  v-model="customerForm.controller_name"
                  placeholder="请输入负责人姓名"
                ></el-input>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="客户关系描述" prop="relation_desc">
                <el-input
                  v-model="customerForm.relation_desc"
                  placeholder="请输入客户关系描述"
                  type="textarea"
                  :rows="2"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </div>

      <!-- 联系地址 -->
      <div class="form-section">
        <h3 class="form-section-title">联系地址</h3>
        <div class="form-container">
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="所在地区" required>
                <RegionCascader
                  ref="regionCascaderRef"
                  v-model="regionData"
                  :placeholder="'请选择省/市/区'"
                  @change="handleRegionChange"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="详细地址" prop="address">
                <el-input v-model="customerForm.address" placeholder="请输入详细地址"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </div>

      <!-- 会员信息 -->
      <div class="form-section">
        <h3 class="form-section-title">会员信息</h3>
        <div class="form-container">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="会员状态">
                <CustomerStatusSelect
                  v-model="customerForm.customer_status"
                  :options="statusOptions"
                />
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="管家">
                <el-select
                  v-model="customerForm.belong_uid"
                  placeholder="请选择管家"
                  clearable
                  :loading="adminList.length === 0"
                >
                  <el-option
                    v-for="admin in adminList"
                    :key="admin.id"
                    :label="admin.name"
                    :value="admin.id"
                  />
                  <el-empty v-if="adminList.length === 0" description="正在加载管家列表..." />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="归属部门">
                <el-input v-model="customerForm.belong_department" readonly></el-input>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="共享员工">
                <el-input v-model="customerForm.share_names" readonly placeholder="请选择共享人员">
                  <template #append>
                    <el-button @click="selectSharedUsers">选择</el-button>
                  </template>
                </el-input>
                <input type="hidden" v-model="customerForm.share_uids" />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </div>

      <!-- 联系人信息 -->
      <div class="form-section">
        <h3 class="form-section-title">联系人信息</h3>
        <div class="form-container">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="联系人" prop="contact_name">
                <el-input
                  v-model="customerForm.contact_name"
                  placeholder="请输入联系人姓名"
                ></el-input>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="联系电话" prop="contact_mobile">
                <el-input
                  v-model="customerForm.contact_mobile"
                  placeholder="请输入联系电话"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="电子邮箱" prop="contact_email">
                <el-input
                  v-model="customerForm.contact_email"
                  placeholder="请输入电子邮箱"
                ></el-input>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="微信" prop="contact_wechat">
                <el-input v-model="customerForm.contact_wechat" placeholder="请输入微信"></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="性别">
                <el-radio-group v-model="customerForm.contact_gender">
                  <el-radio :label="1">男</el-radio>
                  <el-radio :label="2">女</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="QQ号码" prop="contact_qq">
                <el-input v-model="customerForm.contact_qq" placeholder="请输入QQ号码"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </div>

      <!-- 客户介绍 -->
      <div class="form-section">
        <h3 class="form-section-title">客户介绍</h3>
        <div class="form-container">
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="客户介绍" prop="description">
                <el-input
                  v-model="customerForm.description"
                  type="textarea"
                  placeholder="请输入客户介绍信息"
                  :rows="4"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </div>
    </el-form>

    <!-- 主客户选择器 -->
    <PrimaryCustomerSelector
      v-model="primaryCustomerSelectorVisible"
      @select="handlePrimaryCustomerSelect"
    />

    <!-- 用户选择器 -->
    <UserDepartmentSelector
      ref="userDepartmentSelectorRef"
      v-model:visible="userSelectorVisible"
      :multiple="isSelectingCreator ? false : true"
      @select="handleUserSelected"
    />
  </div>
</template>

<script setup lang="ts">
  // 定义事件发射器
  const emit = defineEmits<{
    cancel: []
    submit: [customerData: any]
  }>()

  // 定义props
  const props = defineProps<{
    customerId?: string
  }>()

  // 用户选择器组件引用
  const userDepartmentSelectorRef = ref()

  // 地区选择器组件引用
  const regionCascaderRef = ref()

  // 从外部文件导入所有逻辑
  import {
    // 响应式数据
    formRef,
    customerForm,
    regionData,
    rules,
    userList,
    userDialogVisible,
    adminList,
    userSelectorVisible,
    isSelectingCreator,
    sourceOptions,
    gradeOptions,
    statusOptions,
    primaryCustomerName,
    primaryCustomerSelectorVisible,

    // 方法
    goBack,
    handleUserSelected,
    submitForm,
    init,
    handleRegionChange,
    handlePrimaryChange,
    openPrimaryCustomerSelector,
    handlePrimaryCustomerSelect,
  } from './CustomerEditScript'

  import { CustomerSourceSelector as CustomerSourceSelect } from '@/components/business/customer'
  import { CustomerGradeSelector as CustomerGradeSelect } from '@/components/business/customer'
  import { CustomerStatusSelector as CustomerStatusSelect } from '@/components/business/customer'
  import { CustomerSelector as PrimaryCustomerSelector } from '@/components/business/customer'
  import { RegionCascader } from '@/components/business/region'
  import { UserDepartmentSelector } from '@/components/business/user'
  import { onMounted, defineExpose, watch, ref } from 'vue'

  onMounted(() => {
    // 如果有customerId，则初始化数据
    if (props.customerId) {
      init(props.customerId)
    }
  })

  // 监听customerId变化，重新初始化数据
  watch(
    () => props.customerId,
    newId => {
      if (newId) {
        init(newId)
      }
    },
    { immediate: true }
  )

  // 定义选择录入人的方法，确保打开选择器时数据已加载
  const selectCreator = () => {
    isSelectingCreator.value = true
    // 主动调用选择器的open方法，确保数据加载
    if (userDepartmentSelectorRef.value && userDepartmentSelectorRef.value.open) {
      userDepartmentSelectorRef.value.open()
    } else {
      userSelectorVisible.value = true
    }
  }

  // 定义选择共享人员的方法
  const selectSharedUsers = () => {
    isSelectingCreator.value = false
    if (userDepartmentSelectorRef.value && userDepartmentSelectorRef.value.open) {
      userDepartmentSelectorRef.value.open()
    } else {
      userSelectorVisible.value = true
    }
  }

  defineExpose({
    goBack,
    submitForm,
  })
</script>
